package com.jams.goodox.update;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import com.jams.goodox.BuildConfig;
import com.jams.goodox.SePref;
import com.jams.goodox.TownApplicationLike;
import com.jams.goodox.constant.AppConfig;
import com.jams.goodox.entity.UpdateEntity;
import com.jams.goodox.net.ProtocolManagers;
import com.jams.goodox.net.services.MineService;
import com.jams.goodox.utils.FileUtil;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.ToastUtil;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * @author GuJia
 *         2016年10月27日 上午18;39
 *         app版本检查更新工具类
 */
public class UpDateVersionUtils {
    private static final String ApkFolderPath = Environment.getExternalStorageDirectory() + File.separator + FileUtil.FILE_DIR + File.separator + "apk";//apk文件夹路径
    static final String Download_Apk_Name = BuildConfig.Download_Apk_Name;//更新下载的apk名称
    static final String ApkPath = ApkFolderPath + File.separator + Download_Apk_Name;//apk路径
    static final String Apk_Update_Url = BuildConfig.Apk_Update_Url;//版本更新url

    //检测版本号
    public static void checkAppVersion(final Context context, final boolean needToast) {
        FileUtil.getInstance(context).createFile("/apk");
        MineService mineService = ProtocolManagers.getInstance(context).getService(MineService.class);
        mineService.getAppVersion("android-town").enqueue(new Callback<UpdateEntity>() {
            @Override
            public void onResponse(Call<UpdateEntity> call, Response<UpdateEntity> response) {
                final UpdateEntity updateEntity = response.body();
                if (updateEntity != null && updateEntity.getData() != null) {
                    if (hasNewVersion(context, updateEntity.getData().getVersion())) {
                        //有最新的包
                        if (isExistApk(context, updateEntity.getData().getVersion())) {
                            //本地有最新的安装包
                            UpDateDialog.UpdateHasApkDialog(context,updateEntity.getData().getVersion(), new UpDateDialog.UpDateHasApkActionListener() {
                                @Override
                                public void confirm() {
                                    UpDateVersionUtils.installApk(context);
                                }
                            });
                        } else {
                            if (!needToast && updateEntity.getData().getIsForce() != 1 && !timeCanUpdate(SePref.getUpDateTime(), getSystemTime())) {//一天内不提示升级
                                return;
                            }
                            //本地无apk包，请求下载
                            if (TownApplicationLike.IsDownLoadingApk) {
                                ToastUtil.showLong(context, "新版本正在下载中...");
                                return;
                            }

                            //在下载新apk之前删除原有apk
                            try {
                                File fileOld = new File(ApkFolderPath);
                                if (fileOld.exists()) {
                                    deleteAllFiles(fileOld);
                                    FileUtil.getInstance(context).createFile("/apk");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            UpDateDialog.UpdateDialog(context,
                                    updateEntity.getData().getVersionName(),
                                    updateEntity.getData().getContent(),
                                    updateEntity.getData().getIsForce() == 1,
                                    new UpDateDialog.UpDateActionListener() {
                                        @Override
                                        public void cancel() {

                                        }

                                        @Override
                                        public void confirm() {
                                            if (updateEntity.getData().getIsForce() != 1) {
                                                Intent i = new Intent(context, UpdateService.class);
                                                context.startService(i);
                                            }
                                        }
                                    });
                        }
                    } else {
                        //在下载新apk之前删除uama/apk下面的所有文件
                        try {
                            File fileOld = new File(ApkFolderPath);
                            if (fileOld.exists()) {
                                deleteAllFiles(fileOld);
                                FileUtil.getInstance(context).createFile("/apk");
                            }
                        } catch (Exception e) {
                           e.printStackTrace();
                        }

                        //无需更新
                        if (needToast) {
                            ToastUtil.showLong(context, "已经是最新版本了");
                        }
                    }
                    if (!updateEntity.getStatus().equals(AppConfig.RETURN_SUCCESS)) {
                        ToastUtil.showShort(context, updateEntity.getMsg());
                    }
                } else {
                    ToastUtil.showShort(context, "检测失败，请重试");
                }
            }

            @Override
            public void onFailure(Call<UpdateEntity> call, Throwable t) {
                ToastUtil.showShort(context, "检测失败，请重试");
            }

        });
    }

    private static void deleteAllFiles(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
            if (childFile == null || childFile.length == 0) {
                file.delete();
                return;
            }
            for (File f : childFile) {
                deleteAllFiles(f);
            }
            file.delete();
        }
    }


    //安装下载完成的apk
     static void installApk(Context c) {
        File apkFile = new File(ApkPath);
        if (!apkFile.exists()) {
            ToastUtil.showShort(c, "安装包不存在或已删除");
            return;
        }
        Uri uri = Uri.fromFile(apkFile);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //加这个属性是因为使用Context的startActivity方法的话，就需要开启一个新的task
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        c.startActivity(intent);
    }

    //检查本地是否已存在下载好的最新apk
    private static boolean isExistApk(Context context, String serverVersion) {
        String packageName = "";
        int versionCode = -1;
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(ApkPath, PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;
            packageName = appInfo.packageName;  //得到安装包名称
            versionCode = info.versionCode;       //得到版本信息
        }
        return packageName.equals(context.getPackageName()) && versionCode == StringUtils.toInt(serverVersion);
    }

    //判断是否要更新
    private static boolean hasNewVersion(Context context, String serverVersions) {
        int serverVersion = Integer.parseInt(serverVersions);
        return serverVersion > getVersion(context);
    }

    //获取本地版本
    private static int getVersion(Context context) {
        int version;
        try {
            version = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionCode;
            return version;

        } catch (NameNotFoundException e) {
            Log.i("UpDateVersionUtils:", e.getMessage());
        }
        return -1;
    }

    //比较两个时间是否相差一天
    private static boolean timeCanUpdate(String startTimeStr, String endTimeStr) {
        //格式化时间
        try {
            SimpleDateFormat CurrentTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date beginTime = CurrentTime.parse(startTimeStr);
            Date endTime = CurrentTime.parse(endTimeStr);
            //判断是否大于两天
            if (((endTime.getTime() - beginTime.getTime()) / (24 * 60 * 60 * 1000)) <= 1) {
                return false;
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return true;
    }

    //获取当前时间
    public static String getSystemTime() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return sDateFormat.format(new java.util.Date());
    }
}
